#!/usr/bin/env bash

if [[ 0 -eq `echo $0 | grep -c '^/'` ]]; then
    # relative path
    EXEC_PATH=$(dirname "`pwd`/$0")
else
    # absolute path
    EXEC_PATH=$(dirname "$0")
fi

cd $EXEC_PATH || exit 1

OSNAME=`uname -s`
CMD="../bin/meth"

# environment check
export PATH=$PATH:/tmp/meth
geth_path=`which geth` || ./geth.sh || exit 1
if [[ "Linux" == $OSNAME ]]; then
    parity_path=`which parity` || ./parity.sh || exit 1

    cp ./src_core_helper/linux/_start.sh ./src_core_helper/_start || exit 1
    cp ./src_core_helper/linux/_stop.sh ./src_core_helper/_stop || exit 1
    cp ./src_core_helper/linux/_set_delay.sh ./src_core_helper/_set_delay || exit 1

    #refresh binary symlink
    rm -rf /tmp/meth/geth /tmp/meth/parity
    ln -svf `which geth` /tmp/meth/geth || exit 1
    ln -svf `which parity` /tmp/meth/parity || exit 1
elif [[ "FreeBSD" == $OSNAME ]]; then
    kldload ipfw
    kldload dummynet

    cp ./src_core_helper/freebsd/_start.sh ./src_core_helper/_start || exit 1
    cp ./src_core_helper/freebsd/_stop.sh ./src_core_helper/_stop || exit 1
    cp ./src_core_helper/freebsd/_set_delay.sh ./src_core_helper/_set_delay || exit 1
else
    echo -e "\x1b[31;01mUnsupported platform !!\x1b[00m"
    exit 1
fi

# container ops helper: _start/_stop/_set_delay
rm -rf /tmp/meth/helper
cp -R ./src_core_helper /tmp/meth/helper || exit 1

CC=`which clang` ||
    CC=`which gcc` ||
    exit 1

export CC

# compile
mkdir -p ../bin || exit 1
find .. -type f -name "*.sh" | xargs chmod +x || exit 1
chmod -R u+x /tmp/meth/helper || exit 1
../third-party/build.sh || exit 1
../src/build.sh || exit 1

# start [meth] daemon
LD_LIBRARY_PATH=
for lib in $(find $(dirname `pwd`) -name "*.so" | grep -v '____build____'); do
    LD_LIBRARY_PATH=$(dirname $lib):$LD_LIBRARY_PATH
done
export LD_LIBRARY_PATH
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH" > /tmp/meth/ld_library_path

pkill `basename $CMD`
pkill geth
pkill parity
$CMD &
